<template>
  <!-- 新增/修改 -->
  <el-dialog :title="title" :visible.sync="visible" width="700px" append-to-body :close-on-click-modal="false"
    @close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="small">
      <!-- 站点名称 -->
      <el-form-item label="站点名称" prop="siteName">
        <el-input v-model="form.siteName" placeholder="请输入站点名称" />
      </el-form-item>
      <!-- 地区 -->
      <el-form-item label="地区" prop="region">
        <el-cascader style="width: 100%" v-model="region" :options="regionOptions"
          :props="{ expandTrigger: 'hover' }"></el-cascader>
      </el-form-item>
      <!-- 详细地址 -->
      <el-form-item label="详细地址">
        <el-input v-model="form.detailAddress" type="textarea" placeholder="请输入详细地址"></el-input>
      </el-form-item>
      <!-- 坐标 -->
      <el-form-item label="设备坐标">
        <div class="map-container" id="form-map" style="width: 100%; height: 300px"> </div>
        <div class="map-tip">*点击地图上的位置，更换设备定位*</div>
      </el-form-item>

      <ChargeStrategy v-if="visible" ref="chargeStrategy" :chargeForm="chargeForm"></ChargeStrategy>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import ChargeStrategy from "@/components/ChargeStrategy";
import { addOrUpdateAPI } from "@/api/charge/site";
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  components: { ChargeStrategy },
  props: {
    data: {
      type: Object,
      require: true,
    },
    title: {
      type: String,
      require: true,
    },
    visible: {
      type: Boolean,
      require: true,
    },
  },
  data() {
    return {
      // 表单参数
      form: {},
      region: [],
      regionOptions: [
        {
          value: "江苏省",
          label: "江苏省",
          children: [
            {
              value: "宿迁市",
              label: "宿迁市",
              children: [
                {
                  value: "市辖区",
                  label: "市辖区",
                  children: [
                    {
                      value: "宿城区",
                      label: "宿城区",
                    },
                    {
                      value: "宿豫区",
                      label: "宿豫区",
                    },
                  ],
                },
                {
                  value: "县",
                  label: "县",
                  children: [
                    {
                      value: "沭阳县",
                      label: "沭阳县",
                    },
                    {
                      value: "泗阳县",
                      label: "泗阳县",
                    },
                    {
                      value: "泗洪县",
                      label: "泗洪县",
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
      // 表单校验
      rules: {
        siteName: [
          { required: true, message: "站点名称不能为空", trigger: "blur" },
        ],
        longitude: [
          { required: true, message: "经度不能为空", trigger: "blur" },
        ],
        latitude: [
          { required: true, message: "纬度不能为空", trigger: "blur" },
        ],
      },
      chargeForm: {},

      map: null,
      icons: {
        normal:
          "https://charging-mini.oss-cn-hangzhou.aliyuncs.com/charging-mini/test/user/1852264564548263937/1731581064963-awpsbiF4Ud5Nf090f4bce487db9893e2d5f5e3f97e9f.png",
        selected:
          "https://charging-mini.oss-cn-hangzhou.aliyuncs.com/charging-mini/test/user/1852264564548263937/1731656568429-nGDU4DDtF6Kl008ca122a9ac084ec802a913e1156591.png",
      },
    };
  },
  watch: {
    visible(val) {
      // 数据回填
      if (val) {
        setTimeout(() => {
          this.initAMap({
            longitude: this.data.longitude,
            latitude: this.data.latitude,
          });
        }, 3000);

        this.form = {
          ...this.data,
        };
        this.region = this.form.region ? this.form.region.split("/") : [];
        if (this.data.chargeStrategy) {
          this.chargeForm = JSON.parse(this.data.chargeStrategy);
        }
      }
    },
  },
  methods: {
    // 地图初始化
    initAMap(params) {
      window._AMapSecurityConfig = {
        securityJsCode: "c860797e18c8a6d07dbf9b7d802ef3d4",
      };
      AMapLoader.load({
        key: "013dc7ef41f35fe78a6562c0e73b08d9", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          this.createMap(params);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 绘制地图
    createMap(params) {
      let { longitude, latitude } = params;

      // 检查经纬度是否有效
      if (!longitude || !latitude) {
        console.error('Invalid longitude or latitude');
        return;
      }

      try {
        this.map = new AMap.Map("form-map", {
          // mapStyle: "amap://styles/blue",
          // 设置地图容器id
          viewMode: "3D", // 是否为3D地图模式
          zoom: 11, // 初始化地图级别
          center: [longitude, latitude], // 初始化地图中心点位置
          features: ["bg", "road", "building", "point"],
        });

        // 普通icon
        const normalIcon = new AMap.Icon({
          size: new AMap.Size(42, 42), //图标尺寸
          image: this.icons.normal,
          imageOffset: new AMap.Pixel(0, 0), //图像相对展示区域的偏移量，适于雪碧图等
          imageSize: new AMap.Size(42, 42), //根据所设置的大小拉伸或压缩图片
        });

        // 创建marker并保存引用
        this.currentMarker = new AMap.Marker({
          position: new AMap.LngLat(longitude, latitude),
          icon: normalIcon,
          title: '当前位置',
        });

        this.map.add(this.currentMarker);

        // 添加点击事件监听
        this.map.on('click', (e) => {
          const clickPos = e.lnglat;
          
          // 移除旧marker
          if (this.currentMarker) {
            this.map.remove(this.currentMarker);
          }

          // 创建新marker
          this.currentMarker = new AMap.Marker({
            position: clickPos,
            icon: normalIcon,
            title: '当前位置'
          });

          this.map.add(this.currentMarker);

          // 更新表单数据
          this.form.longitude = clickPos.getLng();
          this.form.latitude = clickPos.getLat();
        });

      } catch (error) {
        console.error('Map initialization error:', error);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = this.getFormParams();
          addOrUpdateAPI(params).then((res) => {
            if (this.form.id) {
              this.$modal.msgSuccess("修改成功");
            } else {
              this.$modal.msgSuccess("新增成功");
            }
            this.$refs["form"].resetFields();
            this.$emit("success");
          });
        }
      });
    },
    // 关闭
    cancel() {
      this.$refs["form"].resetFields();
      this.$emit("cancel");
    },
    // 获取 新增/修改 表单参数
    getFormParams() {
      let chargeStrategy = this.$refs.chargeStrategy.getChargeFormValues();
      let params = {
        id: this.form.id || "",
        siteName: this.form.siteName || "",
        region: this.region.join("/"),
        detailAddress: this.form.detailAddress || "",
        longitude: this.form.longitude || "",
        latitude: this.form.latitude || "",
        chargeStrategy: JSON.stringify(chargeStrategy),
      };

      return params;
    },
  },
};
</script>
<style scoped>
.map-container {
  background-color: #efefef;
}

.map-tip {
  font-size: 12px;
  color: #999;
}
</style>
